package threadMethod;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author： pang-yun
 * @date： 2021-10-14 09:34
 * 功能目的 ：用于 两阶段终止 模式
 */

@Slf4j
public class TwoPhaseTermination {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTerminationDemo demo = new TwoPhaseTerminationDemo();
        demo.start();

        Thread.sleep(3000);


        demo.stop();

    }
}

@Slf4j
class TwoPhaseTerminationDemo {
    private Thread monitor;

    //启动监控线程
    public void start() {
        monitor = new Thread(() -> {
            while (true) {
                Thread thread = Thread.currentThread();
                if (thread.isInterrupted()) {
                    log.info("料理后事！");
                    break;

                }
                try {
                    TimeUnit.SECONDS.sleep(1);  // 睡眠之中  打断会抛出异常
                    log.info("执行监控记录");         // 监控中打断
                } catch (InterruptedException e) {   // 这个异常会将 interrupt 重置为  false
                    e.printStackTrace();
                    //重新设置打断标记
                    thread.interrupt();

                }
            }
        }, "monitor");

        monitor.start();
    }


    //停止监控线程
    public void stop() {
        monitor.interrupt();
    }
}
